﻿using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System;

namespace MG_POS_PC.Util
{
    public class NetworkUtil
    {
        public static string cmdPing(string strIp)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            string pingrst; 
            p.Start(); 
            p.StandardInput.WriteLine("ping " + strIp);
            p.StandardInput.WriteLine("exit");
            string strRst = p.StandardOutput.ReadToEnd();

            if (strRst.IndexOf("(0% loss)")!= -1)
            {
                pingrst = "connected";
            }
            else if (strRst.IndexOf("Destination host unreachable") != -1)
            {
                pingrst = "Destination host unreachable";
            }
            else if (strRst.IndexOf("Request timed out.") != -1)
            {
                pingrst = "Request timed out";
            }
            else if (strRst.IndexOf("Unknown host") != -1)
            {
                pingrst = "Unknown host";
            }
            else
            {
                pingrst = strRst;
            }
            p.Close();
            return pingrst;
        }

        public static string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); 
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                
                return ex.Message;
            }
        }
    }
}
